package zy.service.sort.prepay.impl;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import zy.dao.approve.ApproveRecordDAO;
import zy.dao.base.shop.ShopDAO;
import zy.dao.money.bank.BankDAO;
import zy.dao.money.bank.BankRunDAO;
import zy.dao.sort.dealings.SortDealingsDAO;
import zy.dao.sort.prepay.SortPrepayDAO;
import zy.entity.PageData;
import zy.entity.PageInfo;
import zy.entity.approve.T_Approve_Record;
import zy.entity.base.shop.T_Base_Shop;
import zy.entity.money.bank.T_Money_Bank;
import zy.entity.money.bank.T_Money_BankRun;
import zy.entity.sort.dealings.T_Sort_Dealings;
import zy.entity.sort.prepay.T_Sort_Prepay;
import zy.entity.sys.user.T_Sys_User;
import zy.service.sort.prepay.SortPrepayService;
import zy.util.CommonUtil;
import zy.util.DateUtil;
import zy.util.StringUtil;

@Service
public class SortPrepayServiceImpl implements SortPrepayService{
	@Resource
	private SortPrepayDAO sortPrepayDAO;
	@Resource
	private ApproveRecordDAO approveRecordDAO;
	@Resource
	private SortDealingsDAO sortDealingsDAO;
	@Resource
	private ShopDAO shopDAO;
	@Resource
	private BankDAO bankDAO;
	@Resource
	private BankRunDAO bankRunDAO;
	
	@Override
	public PageData<T_Sort_Prepay> page(Map<String, Object> params) {
		Integer pageSize = (Integer)params.get(CommonUtil.PAGESIZE);
		Integer pageIndex = (Integer)params.get(CommonUtil.PAGEINDEX);
		
		Integer totalCount = sortPrepayDAO.count(params);
		PageInfo pageInfo = new PageInfo(totalCount, pageSize, pageIndex);
		params.put(CommonUtil.START, (pageIndex-1)*pageSize);
		params.put(CommonUtil.END, pageSize);
		
		List<T_Sort_Prepay> list = sortPrepayDAO.list(params);
		PageData<T_Sort_Prepay> pageData = new PageData<T_Sort_Prepay>();
		pageData.setPageInfo(pageInfo);
		pageData.setList(list);
		return pageData;
	}
	
	@Override
	public T_Sort_Prepay load(Integer pp_id) {
		T_Sort_Prepay prepay = sortPrepayDAO.load(pp_id);
		if(prepay != null){
			T_Approve_Record approve_Record = approveRecordDAO.load(prepay.getPp_number(), prepay.getCompanyid());
			if(approve_Record != null){
				prepay.setAr_describe(approve_Record.getAr_describe());
			}
		}
		return prepay;
	}
	
	@Override
	public T_Sort_Prepay load(String number,Integer companyid) {
		return sortPrepayDAO.load(number,companyid);
	}
	
	@Override
	public T_Base_Shop loadShop(String sp_code,Integer companyid) {
		return shopDAO.loadShop(sp_code, companyid);
	}
	
	@Override
	public T_Money_Bank loadBank(String ba_code,Integer companyid) {
		return bankDAO.queryByCode(ba_code, companyid);
	}
	
	@Override
	@Transactional
	public void save(T_Sort_Prepay prepay, T_Sys_User user) {
		if(prepay == null){
			throw new IllegalArgumentException("参数不能为null");
		}
		if(StringUtil.isEmpty(prepay.getPp_shop_code())){
			throw new IllegalArgumentException("店铺不能为空");
		}
		if(StringUtil.isEmpty(prepay.getPp_ba_code())){
			throw new IllegalArgumentException("银行账户不能为空");
		}
		if(StringUtil.isEmpty(prepay.getPp_manager())){
			throw new IllegalArgumentException("经办人不能为空");
		}
		if (prepay.getPp_money() == null || prepay.getPp_money().doubleValue() == 0d) {
			throw new IllegalArgumentException("预收金额不能为0");
		}
		if (prepay.getPp_money() > 0) {
			prepay.setPp_type(0);
		}else {
			prepay.setPp_type(1);
		}
		prepay.setCompanyid(user.getCompanyid());
		prepay.setPp_us_id(user.getUs_id());
		prepay.setPp_maker(user.getUs_name());
		prepay.setPp_ar_state(CommonUtil.AR_STATE_NOTAPPROVE);
		prepay.setPp_sysdate(DateUtil.getCurrentTime());
		sortPrepayDAO.save(prepay);
	}
	
	@Override
	@Transactional
	public void update(T_Sort_Prepay prepay, T_Sys_User user) {
		if(prepay == null){
			throw new IllegalArgumentException("参数不能为null");
		}
		if(StringUtil.isEmpty(prepay.getPp_shop_code())){
			throw new IllegalArgumentException("店铺不能为空");
		}
		if(StringUtil.isEmpty(prepay.getPp_ba_code())){
			throw new IllegalArgumentException("银行账户不能为空");
		}
		if(StringUtil.isEmpty(prepay.getPp_manager())){
			throw new IllegalArgumentException("经办人不能为空");
		}
		if (prepay.getPp_money() == null || prepay.getPp_money().doubleValue() == 0d) {
			throw new IllegalArgumentException("预收金额不能为0");
		}
		T_Sort_Prepay oldPrepay = sortPrepayDAO.check(prepay.getPp_number(), user.getCompanyid());
		if(oldPrepay == null || !CommonUtil.AR_STATE_FAIL.equals(oldPrepay.getPp_ar_state())){
			throw new RuntimeException("单据已修改，请勿重复提交");
		}
		if (prepay.getPp_money() > 0) {
			prepay.setPp_type(0);
		}else {
			prepay.setPp_type(1);
		}
		prepay.setCompanyid(user.getCompanyid());
		prepay.setPp_us_id(user.getUs_id());
		prepay.setPp_maker(user.getUs_name());
		prepay.setPp_ar_state(CommonUtil.AR_STATE_NOTAPPROVE);
		prepay.setPp_ar_date(null);
		prepay.setPp_sysdate(DateUtil.getCurrentTime());
		sortPrepayDAO.update(prepay);
	}
	
	@Override
	@Transactional
	public T_Sort_Prepay approve(String number, T_Approve_Record record, T_Sys_User user) {
		if (number == null) {
			throw new IllegalArgumentException("参数number不能为null");
		}
		T_Sort_Prepay prepay = sortPrepayDAO.check(number, user.getCompanyid());
		if(prepay == null){
			throw new RuntimeException("单据不存在");
		}
		if(!CommonUtil.AR_STATE_NOTAPPROVE.equals(prepay.getPp_ar_state())){
			throw new RuntimeException("单据已经审核");
		}
		T_Base_Shop shop = shopDAO.loadShop(prepay.getPp_shop_code(), user.getCompanyid());
		shop.setSp_prepay(shop.getSp_prepay() + prepay.getPp_money());
		if (CommonUtil.AR_STATE_APPROVED.equals(record.getAr_state())
				&& prepay.getPp_money() < 0 && shop.getSp_prepay() < 0) {// 退款则验证店铺预收款余额是否足够
			throw new RuntimeException("店铺预收款余额不足");
		}
		//更新单据审核状态
		prepay.setPp_ar_state(record.getAr_state());
		prepay.setPp_ar_date(DateUtil.getCurrentTime());
		sortPrepayDAO.updateApprove(prepay);
		//保存审核记录表
		record.setAr_number(number);
		record.setAr_sysdate(DateUtil.getCurrentTime());
		record.setAr_us_name(user.getUs_name());
		record.setAr_type("t_sort_prepay");
		record.setCompanyid(user.getCompanyid());
		approveRecordDAO.save(record);
		if(!CommonUtil.AR_STATE_APPROVED.equals(prepay.getPp_ar_state())){//审核不通过，则直接返回
			return prepay;
		}
		//3.审核通过
		//更新店铺财务&生成往来明细账
		shopDAO.updatePrepay(shop);
		T_Sort_Dealings dealings = new T_Sort_Dealings();
		dealings.setDl_shop_code(prepay.getPp_shop_code());
		dealings.setDl_number(prepay.getPp_number());
		if(prepay.getPp_money()>0){
			dealings.setDl_type(CommonUtil.SORTDEALINGS_TYPE_YSK);
		}else {
			dealings.setDl_type(CommonUtil.SORTDEALINGS_TYPE_YSTK);
		}
		dealings.setDl_discount_money(0d);
		dealings.setDl_receivable(0d);
		dealings.setDl_received(prepay.getPp_money());
		dealings.setDl_debt(shop.getSp_receivable()-shop.getSp_received()-shop.getSp_prepay());
		dealings.setDl_date(DateUtil.getCurrentTime());
		dealings.setDl_manager(user.getUs_name());
		dealings.setDl_remark(prepay.getPp_remark());
		dealings.setDl_sysdate(DateUtil.getCurrentTime());
		dealings.setCompanyid(user.getCompanyid());
		sortDealingsDAO.save(dealings);
		//银行账目及流水
		T_Money_Bank bank = bankDAO.queryByCode(prepay.getPp_ba_code(), user.getCompanyid());
		if(bank != null){
			bank.setBa_balance(bank.getBa_balance()+prepay.getPp_money());
			bankDAO.updateBalanceById(bank);
			T_Money_BankRun bankRun = new T_Money_BankRun();
			bankRun.setBr_ba_code(prepay.getPp_ba_code());
			bankRun.setBr_balance(bank.getBa_balance());
			bankRun.setBr_bt_code(CommonUtil.BANKRUN_SORTPREPAY);
			bankRun.setBr_date(prepay.getPp_date());
			if(prepay.getPp_money()>0){
				bankRun.setBr_enter(Math.abs(prepay.getPp_money()));
			}else {
				bankRun.setBr_out(Math.abs(prepay.getPp_money()));
			}
			bankRun.setBr_manager(prepay.getPp_manager());
			bankRun.setBr_number(prepay.getPp_number());
			bankRun.setBr_remark(prepay.getPp_remark());
			bankRun.setBr_shop_code(bank.getBa_shop_code());
			bankRun.setBr_sysdate(DateUtil.getCurrentTime());
			bankRun.setCompanyid(user.getCompanyid());
			bankRunDAO.save(bankRun);
		}
		return prepay;
	}
	
	@Override
	@Transactional
	public T_Sort_Prepay reverse(String number, T_Sys_User user) {
		if (number == null) {
			throw new IllegalArgumentException("参数number不能为null");
		}
		T_Sort_Prepay prepay = sortPrepayDAO.check(number, user.getCompanyid());
		if(prepay == null){
			throw new RuntimeException("单据不存在");
		}
		if(!CommonUtil.AR_STATE_APPROVED.equals(prepay.getPp_ar_state())){
			throw new RuntimeException("单据未审核或审核未通过");
		}
		T_Base_Shop shop = shopDAO.loadShop(prepay.getPp_shop_code(), user.getCompanyid());
		shop.setSp_prepay(shop.getSp_prepay() - prepay.getPp_money());
		if (prepay.getPp_money() > 0 && shop.getSp_prepay() < 0) {// 收款则验证店铺预收款余额是否足够
			throw new RuntimeException("店铺预收款余额不足");
		}
		//更新单据审核状态
		prepay.setPp_ar_state(CommonUtil.AR_STATE_NOTAPPROVE);
		prepay.setPp_ar_date(DateUtil.getCurrentTime());
		sortPrepayDAO.updateApprove(prepay);
		//保存审核记录表
		T_Approve_Record record = new T_Approve_Record();
		record.setAr_state(CommonUtil.AR_STATE_REVERSE_APPROVE);
		record.setAr_describe(user.getUs_name()+"反审核单据");
		record.setAr_number(number);
		record.setAr_sysdate(DateUtil.getCurrentTime());
		record.setAr_us_name(user.getUs_name());
		record.setAr_type("t_sort_prepay");
		record.setCompanyid(user.getCompanyid());
		approveRecordDAO.save(record);
		//更新批发客户财务&删除往来明细账
		shopDAO.updatePrepay(shop);
		
		T_Sort_Dealings dealings = new T_Sort_Dealings();
		dealings.setDl_shop_code(prepay.getPp_shop_code());
		dealings.setDl_number(prepay.getPp_number());
		if(prepay.getPp_money()>0){
			dealings.setDl_type(CommonUtil.SORTDEALINGS_TYPE_YSK);
		}else {
			dealings.setDl_type(CommonUtil.SORTDEALINGS_TYPE_YSTK);
		}
		dealings.setDl_discount_money(0d);
		dealings.setDl_receivable(0d);
		dealings.setDl_received(-prepay.getPp_money());
		dealings.setDl_debt(shop.getSp_receivable()-shop.getSp_received()-shop.getSp_prepay());
		dealings.setDl_date(DateUtil.getCurrentTime());
		dealings.setDl_manager(user.getUs_name());
		dealings.setDl_remark("反审核恢复账目往来明细");
		dealings.setDl_sysdate(DateUtil.getCurrentTime());
		dealings.setCompanyid(user.getCompanyid());
		sortDealingsDAO.save(dealings);
		//银行账目及流水
		T_Money_Bank bank = bankDAO.queryByCode(prepay.getPp_ba_code(), user.getCompanyid());
		if(bank != null){
			bank.setBa_balance(bank.getBa_balance() - prepay.getPp_money());
			bankDAO.updateBalanceById(bank);
			T_Money_BankRun bankRun = new T_Money_BankRun();
			bankRun.setBr_ba_code(prepay.getPp_ba_code());
			bankRun.setBr_balance(bank.getBa_balance());
			bankRun.setBr_bt_code(CommonUtil.BANKRUN_SORTPREPAY);
			bankRun.setBr_date(prepay.getPp_date());
			if(prepay.getPp_money()>0){
				bankRun.setBr_out(Math.abs(prepay.getPp_money()));
			}else {
				bankRun.setBr_enter(Math.abs(prepay.getPp_money()));
			}
			bankRun.setBr_manager(user.getUs_name());
			bankRun.setBr_number(prepay.getPp_number());
			bankRun.setBr_remark("反审核恢复账目");
			bankRun.setBr_shop_code(bank.getBa_shop_code());
			bankRun.setBr_sysdate(DateUtil.getCurrentTime());
			bankRun.setCompanyid(user.getCompanyid());
			bankRunDAO.save(bankRun);
		}
		return prepay;
	}
	
	@Override
	@Transactional
	public void del(String number, Integer companyid) {
		T_Sort_Prepay prepay = sortPrepayDAO.check(number, companyid);
		if(prepay == null){
			throw new RuntimeException("单据不存在");
		}
		if(!CommonUtil.AR_STATE_NOTAPPROVE.equals(prepay.getPp_ar_state()) && !CommonUtil.AR_STATE_FAIL.equals(prepay.getPp_ar_state())){
			throw new RuntimeException("单据已审核通过不能删除！");
		}
		sortPrepayDAO.del(number, companyid);
	}
	
}
